const Koa = require('koa');
const formidable = require('formidable');
const app = new Koa();

var fs = require("fs");
 
app.on('error', (err) => {
  console.error('server error', err);
});
 
app.use(async (ctx, next) => {
  if (ctx.url === '/api/upload' && ctx.method.toLowerCase() === 'post') {
    const form = formidable({ 
      multiples: true,
      encoding:"utf-8",
      uploadDir:"./upload_tmp",
      keepExtensions:true });
 
    // not very elegant, but that's for now if you don't want touse `koa-better-body`
    // or other middlewares.
    await new Promise((resolve, reject) => {
      form.parse(ctx.req, (err, fields, files) => {

        var message={};

        if (err) {
          reject(err);
          message={"content":"上传失败"};
          return;
        }else
        {
          message={"content":"上传成功"};
        }
        Object.keys(files).forEach(function(name) {
          console.log('name:' + name+";file:"+files[name].path);

          let timestamps = Math.round(new Date().getTime() / 1000).toString();
          let newPath='./upload_tmp/'+timestamps+files[name].name;
          
          fs.rename(files[name].path, newPath, function (err) {
            if(err)
            {
             message={"content":"上传失败"};
            }else
            {
              message={"content":"上传成功"};
            }
            console.log(message);
          })
        })
        
        ctx.set('Content-Type', 'application/json');
        ctx.status = 200;
        ctx.state = {fields, files ,message};//fs.rename异步导致message为空
        ctx.body = JSON.stringify(ctx.state, null, 2);
        resolve();
      });
    });
    await next();
    return;
  }
 
  // show a file upload form
  ctx.set('Content-Type', 'text/html');
  ctx.status = 200;
  ctx.body = `
    <h2>With <code>"koa"</code> npm package</h2>
    <form action="/api/upload" enctype="multipart/form-data" method="post">
    <div>Text field title: <input type="text" name="title" /></div>
    <div>File: <input type="file" name="koaFiles" multiple="multiple" /></div>
    <input type="submit" value="Upload" />
    </form>
  `;
});
 
app.use((ctx) => {
  console.log('The next middleware is called');
  console.log('Results:', ctx.state);
});
 
app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000 ...');
});